#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import cgi
import wsgiref.handlers
import os
import sys
import datetime

sys.path.append("./feedparser")

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api.urlfetch import InvalidURLError
from google.appengine.ext.db import *
from django.utils import simplejson
import feedparser
from model import *
import view

class MainPage(webapp.RequestHandler):
  def get(self):
    TEST = False;
    user = users.get_current_user()

    # Redirection in login page if not logged yet.
    if user:
        query = VIEW_DATA.all()
        nbviewdata=query.filter('user',user).count()
        if nbviewdata == 0:
            viewdata = VIEW_DATA(user=user,type="default",rssId='')
            db.put(viewdata)
        else:
            viewdata = VIEW_DATA.all().filter('user', user).fetch(1)[0]
        rssId = self.request.get('rssId')
        queryRssUser = GqlQuery("SELECT * FROM RSS_USER WHERE user = :1 ", user)
        rss_list = []
        if rssId and rssId != '':
            rss=RSS.get(rssId)
            rss.updateArticles(user,test=TEST)
            query = GqlQuery("SELECT * FROM RSS_ARTICLE_USER WHERE user = :1 AND rss = :2 ORDER BY date DESC ",
                             user, rss)
            viewdata.rssId = rssId
            db.put(viewdata)             
        else:
            query = GqlQuery("SELECT * FROM RSS_ARTICLE_USER WHERE user = :1 ORDER BY date DESC ", user)
            viewdata.rssId = ''
            db.put(viewdata)                  
        
        for rss_user in queryRssUser:
            rss_list.append(rss_user.rss)
            if rssId == None or rssId == '':
                # Update all articles of the user
                rss_user.rss.updateArticles(user,test=TEST)
        
        # Get the current page and compute total page
        page = self.request.get('page')
        if page:
            page = int(page)
        else :
            page = 1
        offset = view.NB_ELT_PAR_PAGE*(page-1)
        nbpage = int(query.count()/view.NB_ELT_PAR_PAGE + 1)
        
        # Get rss_article_users
        rss_article_users = query.fetch(limit=view.NB_ELT_PAR_PAGE,offset=offset)
        articles = []
        for rss_article_user in rss_article_users:
            articles.append(rss_article_user.rss_article)
        if self.request.get('view') and self.request.get('view') == 'image':
            viewdata.type = 'image'
            db.put(viewdata)
        elif self.request.get('view') and self.request.get('view') == 'default':
            viewdata.type = 'default'
            db.put(viewdata)
        if viewdata.type == 'image':
            view.requestImageView(self,rss_list,articles,nbpage,comment='',viewdata=viewdata)
        else:
            # Default view
            menu = view.MENU %{'rssId':viewdata.rssId}
            template_values = {'rss_list':rss_list, 'rss_article_users':rss_article_users ,'articles':articles, 'menu':menu, 'navigator': view.getNavigator(nbpage, page, viewdata),'viewdata':viewdata}     
            path = os.path.join(os.path.dirname(__file__), 'html/newsreader.html')        
            self.response.headers['Content-Type'] = 'text/html; charset=UTF-8'
            self.response.out.write(template.render(path, template_values))
    else:
        self.redirect(users.create_login_url(self.request.uri))

class AddUrl(webapp.RequestHandler):
    def post(self):
        comment = ''    
        newUrl = self.request.get('content')
        try:
            user = users.get_current_user()
            # Search if this url is already in base
            query = GqlQuery("SELECT * FROM RSS WHERE url = :1", newUrl)
            rss = query.get()
            # Search if the current user has this url already
            if rss != None:
                query = GqlQuery("SELECT * FROM RSS_USER WHERE user = :1 and rss = :2", user, rss)
                rss_user = query.count()
                if rss_user == 0:
                    # Links the rss to the current user
                    rss_user = RSS_USER(user=user, rss=rss.key())
                    rss_user.put()
                    comment = 'Le flux a bien été ajouté.'
                else:
                    # rss is already linked to the current user
                    comment = 'Vous avez déjà enregistré ce flux'
            else:
                result = urlfetch.fetch(newUrl)
                d = feedparser.parse(result.content)
                if d != None:
                    # Create new url
                    rss = RSS(url=newUrl)
                    if 'title' not in d.feed.keys():
                        title = 'No Title'
                    else :
                        title = d.feed.title
                        rss.title = title
                    if 'subtitle' not in d.feed.keys():
                        subtitle = 'No subtitle'
                    else:
                        subtitle = d.feed.subtitle
                        rss.subtitle = subtitle
                    if 'language' in d.feed.keys():
                        rss.language = d.feed.language
                    else:
                        rss.language = 'en'
                    # New url
                    rss.put()
                    # Add this rss to the user ones
                    rss_user = RSS_USER(user=user, rss=rss.key())
                    rss_user.put()
                    comment = "Le flux a bien été ajouté."
                else:
                    comment = 'Cet url est ne correspond pas à un flux RSS'
        except InvalidURLError:
           comment = 'Cet url est invalide'
        template_values = {'comment':comment, 'menu': view.MENU %{'rssId':''}}
        path = os.path.join(os.path.dirname(__file__), 'html/addUrl.html')
        self.response.headers['Content-Type'] = 'text/html; charset=UTF-8'
        self.response.out.write(template.render(path, template_values))
    
class MarkAsRead(webapp.RequestHandler):
    def get(self,key):
        article = RSS_ARTICLE_USER.get(key)
        article.read = not article.read
        article.put()
        readText='%(read)s'%{'read':article.read}
        self.response.headers['Content-Type']  = 'application/json'
        self.response.out.write(simplejson.dumps({'readText': readText}))
        
        
class NewUrl(webapp.RequestHandler):
  def get(self):
      template_values = {'comment':'', 'menu': view.MENU}
      path = os.path.join(os.path.dirname(__file__), 'html/addUrl.html')        
      self.response.headers['Content-Type'] = 'text/html; charset=UTF-8'
      self.response.out.write(template.render(path, template_values))

class RemoveUrl(webapp.RequestHandler):
  def get(self):
    key = self.request.get('key')
    rss = RSS.get(key)

    # delete articles of this rss
    query = db.GqlQuery("SELECT * FROM RSS_ARTICLE WHERE rss = :1", key)
    for a in query: 
      if a != None:
	db.delete(a)
    rss.delete()
    rss_list = RSS.all()
    template_values = {'rss_list':rss_list}
    path = os.path.join(os.path.dirname(__file__), 'html/adminUrl.html')
    self.response.out.write(template.render(path, template_values))

class UpdateAll(webapp.RequestHandler):
  def get(self):
    rss_list = RSS.all()
    for rss in rss_list:
    	#result = urlfetch.fetch(rss.url)
    	#d = feedparser.parse(result.content)
    	rss.updateArticles(user=users.get_current_user(),forced=True)
	#self.updateArticles(d.entries,rss)
    template_values = {'rss_list':rss_list, 'articles':None, 'menu': view.MENU, 'navigator': None}     
    path = os.path.join(os.path.dirname(__file__), 'html/newsreader.html')        
    self.response.headers['Content-Type'] = 'text/html; charset=UTF-8'
    self.response.out.write(template.render(path, template_values))

class Display(webapp.RequestHandler):
  def get(self):
    query = db.Query(RSS_ARTICLE)
    query.order('-date')
    articles = query.fetch(limit=20)
    articles_updated = []
    for a in articles:
      try:
        if a.rss != None:
          articles_updated.append(a)
      except:
	pass
    template_values = {'articles':articles_updated, 'error':''}
    path = os.path.join(os.path.dirname(__file__), 'display-articles.html')
    self.response.headers["Content-Type"] = "text/html;charset=UTF-8"
    self.response.out.write(template.render(path, template_values))
class ResetAll(webapp.RequestHandler):
  def get(self):
    articles = RSS_ARTICLE.all()
    for a in articles:
        db.delete(a)
    for rss in RSS.all():
        db.delete(rss)
    for rss_user in RSS_USER.all():
        db.delete(rss_user)
    for  rss_user_article in RSS_ARTICLE_USER.all():
        db.delete(rss_user_article)
    template_values = {'rss_list':[], 'articles':[], 'menu':view.MENU %{'rssId': ''}, 'navigator': ''}
    path = os.path.join(os.path.dirname(__file__), 'html/newsreader.html')
    self.response.headers['Content-Type'] = 'text/html; charset=UTF-8'
    self.response.out.write(template.render(path, template_values))
 
class Info(webapp.RequestHandler):
  def get(self):
    feed = None
    entry = None
    newUrl = self.request.get('content')
    if newUrl != None and newUrl != '' :
      result = urlfetch.fetch(newUrl)
      d = feedparser.parse(result.content)
      feed = d.feed
      if d.entries != None and d.entries != []:
        entry = d.entries[0]
      error = ''
    else:
      error = "url introuvable"
    template_values = {'feed':feed, 'error':error, 'entry':entry}
    path = os.path.join(os.path.dirname(__file__), 'test-info.html')
    self.response.out.write(template.render(path, template_values))      
def main():
  application = webapp.WSGIApplication(
                    [('/', MainPage),
                    ('/home', MainPage),
					('/markAsRead/([^/]+)', MarkAsRead),
					('/newUrl', NewUrl),
					#('/manageUrls', ManageUrls),
					('/addUrl', AddUrl),
					('/updateAll', UpdateAll),
					('/display', Display),
					('/resetAll', ResetAll),
					('/info', Info),
					('/removeUrl', RemoveUrl)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
